<?php

namespace App\Models\Store\User;

class UserApplyRecordsModel extends BaseUserModel
{
    protected $table = 'user_apply_records';

    // 账号状态 0 待审核 1 审核通过 2 审核拒绝
    const STATUS_WAIT     = 0; // 待审核
    const STATUS_APPROVED = 1; // 审核通过
    const STATUS_REJECTED = 2; // 审核拒绝

    /**
     * 总条数
     * @param array $params
     * @return int
     */
    public function total(array $params): int
    {
        $query = $this;
        if (!empty($params['keyword'])) {
            $whereRaw = '(real_name like "%' . $params['keyword'] . '%"' .
                        ' or phone like "%' . $params['keyword'] . '%"' .
                        ' or store_ranch.name like "%' . $params['keyword'] . '%")';
            if (is_numeric($params['keyword'])) {
                $whereRaw = trim($whereRaw, ')');
                $whereRaw .= ' or cast(store_user_apply_records.id as char) like "%' . $params['keyword'] . '%")';
            }
            $query = $query->whereRaw($whereRaw);
        }

        return $query->join('store_users', 'store_users.id', '=', 'store_user_apply_records.store_user_id')
                     ->join('store_ranch', 'store_ranch.store_user_id', '=', 'store_user_apply_records.store_user_id')
                     ->where('store_user_apply_records.deleted', self::DELETED_NO)
                     ->count();
    }

    /**
     * 用户申请列表
     * @param array $params
     * @param array $fields
     * @return array
     */
    public function list(array $params, array $fields = self::QUERY_DEFAULT_FIELDS): array
    {
        $query = $this;
        if (!empty($params['keyword'])) {
            $whereRaw = '(real_name like "%' . $params['keyword'] . '%"' .
                        ' or phone like "%' . $params['keyword'] . '%"' .
                        ' or store_ranch.name like "%' . $params['keyword'] . '%")';
            if (is_numeric($params['keyword'])) {
                $whereRaw = trim($whereRaw, ')');
                $whereRaw .= ' or cast(store_user_apply_records.id as char) like "%' . $params['keyword'] . '%")';
            }
            $query = $query->whereRaw($whereRaw);
        }

        return $query->select($fields)
                     ->join('store_users', 'store_users.id', '=', 'store_user_apply_records.store_user_id')
                     ->join('store_ranch', 'store_ranch.store_user_id', '=', 'store_user_apply_records.store_user_id')
                     ->where('store_user_apply_records.deleted', self::DELETED_NO)
                     ->orderBy('id', 'desc')
                     ->offset((CURRENT_PAGE - 1) * PAGE_SIZE)
                     ->limit(PAGE_SIZE)
                     ->get()
                     ->toArray();
    }
}
